package com.yunlong.softpark.controller;

import com.yunlong.softpark.core.exception.SysException;
import com.yunlong.softpark.core.support.web.controller.BaseController;
import com.yunlong.softpark.core.wrapper.ResultWrapper;
import com.yunlong.softpark.dto.LoginSuccessDto;
import com.yunlong.softpark.dto.MessageSuccessDto;
import com.yunlong.softpark.dto.TokenInfo;
import com.yunlong.softpark.dto.UserInfo;
import com.yunlong.softpark.form.*;
import com.yunlong.softpark.redis.RedisRepository;
import com.yunlong.softpark.service.RecordService;
import com.yunlong.softpark.service.SoftwareService;
import com.yunlong.softpark.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * @Author: Cui
 * @Date: 2020/7/23
 * @Description:
 */
@Api(value = "UserController", tags = {"用户接口"})
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController extends BaseController<UserInfo> {

    @Autowired
    UserService userService;

    @Autowired
    RedisRepository redisRepository;

    @Autowired
    SoftwareService softwareService;

    @Autowired
    RecordService recordService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 注册
     * @param registerForm
     */
    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public ResultWrapper register(@Valid @RequestBody RegisterForm registerForm,BindingResult bindingResult){
        try {
            validateParams(bindingResult);
            MessageSuccessDto messageSuccessDto = userService.register(registerForm);
            return ResultWrapper.successWithData(messageSuccessDto);
        }catch (SysException e){
            log.info("UserController.register");
            return ResultWrapper.failure(e.getMessage());
        }
    }

    /**
     * 密码登录
     * @param loginForm
     * @return
     */
    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public ResultWrapper login(@Valid@RequestBody LoginForm loginForm,BindingResult bindingResult,
                               HttpServletRequest request){
        try {
//            参数校验
            validateParams(bindingResult);
            System.out.println(request.getRemoteAddr());
            LoginSuccessDto loginSuccessDto = userService.login(loginForm);
            String userId = redisRepository.selectAccessToken(loginSuccessDto.getAccessToken());
            try {
                recordService.saveRecord(request.getRemoteAddr(),1,null,userId);
            }catch (DataIntegrityViolationException e){
                log.info("record表违反唯一约束，但是插入成功");
                return ResultWrapper.successWithData(loginSuccessDto);
            }
            return ResultWrapper.successWithData(loginSuccessDto);
        }catch (SysException e){
            log.info("UserController.login");
            return ResultWrapper.failure(e.getMessage());
        }
    }

    /**
     * 验证码登录
     * @param loginCodeForm
     * @return
     */
    @ApiOperation(value = "用户验证码登录")
    @PostMapping("/loginCode")
    public ResultWrapper login(@Valid@RequestBody LoginCodeForm loginCodeForm,BindingResult bindingResult){
        try {
            validateParams(bindingResult);
            LoginSuccessDto loginSuccessDto = userService.login(loginCodeForm);
            return ResultWrapper.successWithData(loginSuccessDto);
        }catch (SysException e){
            log.info("UserController.login");
            return ResultWrapper.failure(e.getMessage());
        }
    }

    /**
     * 更新手机号
     * @param updatePhoneForm
     * @return
     */
    @ApiOperation("更换手机号")
    @PostMapping("/updatePhone")
    public ResultWrapper updatePhone(@Valid@RequestBody UpdatePhoneForm updatePhoneForm,BindingResult bindingResult){
        try{
            validateParams(bindingResult);
            userService.updatePhone(updatePhoneForm,getCurrentUserInfo().getUserId());
            return ResultWrapper.success();
        }catch (SysException e){
            return ResultWrapper.failure();
        }

    }

    /**
     * 忘记密码
     * @param forgetPasswordForm
     * @return
     */
    @ApiOperation(value = "忘记密码")
    @PostMapping("/forgetPassword")
    public ResultWrapper forgetPassword(@Valid@RequestBody ForgetPasswordForm forgetPasswordForm,
                                        BindingResult bindingResult){
        try {
            validateParams(bindingResult);
            return ResultWrapper.successWithData(userService.forgetPassword(forgetPasswordForm));
        }catch (Exception e){
            log.info("UserController.forgetPassword");
            return ResultWrapper.failure(e.getMessage());
        }
    }


    /**
     * 获取个人中心
     * @return
     */
    @ApiOperation(value = "获取个人中心")
    @GetMapping("/getUserInfo")
    public ResultWrapper getUserInfo(){
        return ResultWrapper.successWithData(userService.getUserInfo(getCurrentUserInfo().getUserId()));
    }

    /**
     * 修改个人中心
     * @param updateInfoForm
     * @return
     */
    @ApiOperation(value = "修改个人中心")
    @PostMapping("/updateInfo")
    public ResultWrapper updateInfo(@Valid@RequestBody UpdateInfoForm updateInfoForm,BindingResult bindingResult){
        try {
            validateParams(bindingResult);
            return ResultWrapper.successWithData(userService.updateInfo(updateInfoForm,
                    getCurrentUserInfo().getUserId()));
        }catch (Exception e){
            log.info("UserController.updateInfo");
            return ResultWrapper.failure(e.getMessage());
        }

    }

    /**
     * 通过旧密码修改新密码
     * @param updatePassByOldForm
     * @return
     */
    @ApiOperation(value = "通过旧密码修改密码")
    @PostMapping("/updatePasswordByOld")
    public ResultWrapper updatePasswordByOld(@Valid@RequestBody UpdatePassByOldForm updatePassByOldForm,BindingResult bindingResult){
        try {
            validateParams(bindingResult);
            return ResultWrapper.successWithData(userService.updatePasswordByOld(updatePassByOldForm,getCurrentUserInfo().getUserId()));
        }catch (SysException e){
            log.info("UserController.updatePasswordByOld");
            return ResultWrapper.failure(e.getMessage());
        }
    }

    /**
     * 通过验证码修改密码
     * @param updatePassByCodeForm
     * @return
     */
    @ApiOperation(value = "通过验证码修改密码")
    @PostMapping("/updatePasswordByCode")
    public ResultWrapper updatePasswordByCode(@Valid@RequestBody UpdatePassByCodeForm updatePassByCodeForm,
                                              BindingResult bindingResult){
        try {
            validateParams(bindingResult);
            return ResultWrapper.successWithData(userService.
                    updatePasswordByCode(updatePassByCodeForm,
                            getCurrentUserInfo().getUserId()));
        }catch (SysException e){
            log.info("UserController.updatePasswordByCode");
            return ResultWrapper.failure(e.getMessage());
        }
    }

    /**
     * 获取过去发布的软件
     * @param page
     * @return
     */
    @ApiOperation(value = "获取历史发布的软件")
    @GetMapping("/getHistorySoft")
    public ResultWrapper getHistorySoft(@RequestParam("page") Integer page){
        return ResultWrapper.successWithData(userService.getHistoryPublished(getCurrentUserInfo().getUserId(),page));
    }

    /**
     * 退出登录
     * @return
     */
    @ApiOperation(value = "退出登录")
    @GetMapping("/logout")
    public ResultWrapper logout(){
        userService.logout(getCurrentUserInfo().getUserId());
        return ResultWrapper.success();
    }

    /**
     * 上传
     * @param publishedForm
     * @return
     */
    @ApiOperation("发布软件")
    @PostMapping("/publish")
    public ResultWrapper publishSoft(@Valid@RequestBody PublishedForm publishedForm,
                                     BindingResult bindingResult,
                                     HttpServletRequest request){

        try {
            validateParams(bindingResult);
            String softId = softwareService.publishedSoft(publishedForm, getCurrentUserInfo().getUserId());
            recordService.saveRecord(request.getRemoteAddr(),7,softId,getCurrentUserInfo().getUserId());
            MessageSuccessDto messageSuccessDto = new MessageSuccessDto();
            messageSuccessDto.setMessage("上传成功，正在等待管理员审核！");
            return ResultWrapper.successWithData(messageSuccessDto);
        }catch (DataIntegrityViolationException e){
            log.info("record表违反唯一约束，但是插入成功");
            MessageSuccessDto messageSuccessDto = new MessageSuccessDto();
            messageSuccessDto.setMessage("上传成功，正在等待管理员审核！");
            return ResultWrapper.successWithData(messageSuccessDto);
        } catch (Exception e){
            log.info("UserController.publishSoft");
            return ResultWrapper.failure(e.getMessage());
        }
    }

    /**
     * 上传
     * @param updateSoftForm
     * @return
     */
    @ApiOperation("更新软件信息")
    @PostMapping("/updateSoft")
    public ResultWrapper updateSoft(@Valid@RequestBody UpdateSoftForm updateSoftForm,BindingResult bindingResult){
        try {
            validateParams(bindingResult);
            return ResultWrapper.successWithData(softwareService.updateSoft(updateSoftForm,getCurrentUserInfo().getUserId()));
        }catch (Exception e){
            log.info("UserController.updateSoft");
            return ResultWrapper.failure(e.getMessage());
        }
    }

}
